#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
语音助手Demo
功能：
1. 等待唤醒词检测
2. 检测到唤醒词后播放系统音效
3. 开始基于VAD的录音（3秒间隔）
4. 语音转文字
5. 循环进行VAD录音和识别
"""

import time
import threading
from voice_module.voice_interface import VoiceInterface

class VoiceAssistantDemo:
    def __init__(self):
        # 指定配置文件路径以确保语音识别模块正确初始化
        config_path = "voice_module/config/voice_config.yaml"
        self.voice = VoiceInterface(config_path=config_path)
        self.is_running = False
        self.wake_detected = False
        self.wake_thread = None
        
    def initialize(self):
        """初始化所有语音模块"""
        print("正在初始化语音助手...")
        
        # 添加配置调试信息
        print(f"🔧 配置文件路径: {getattr(self.voice, 'config_path', 'Unknown')}")
        
        # 检查STT配置
        stt_config = self.voice.config.get('speech_to_text', {})
        print(f"🔧 STT配置存在: {bool(stt_config)}")
        if stt_config:
            print(f"🔧 STT app_id: {stt_config.get('app_id', 'Missing')[:8]}...")
            print(f"🔧 STT api_key: {stt_config.get('api_key', 'Missing')[:8]}...")
            print(f"🔧 STT api_secret: {stt_config.get('api_secret', 'Missing')[:8]}...")
        
        # 初始化所有模块
        success, message, _ = self.voice.initialize_all()
        if not success:
            print(f"初始化失败: {message}")
            return False
        
        # 检查模块状态
        print("🔍 检查各模块状态:")
        status_success, status_msg, module_status = self.voice.get_module_status()
        if status_success:
            for module, is_ready in module_status.items():
                status_icon = "✅" if is_ready else "❌"
                print(f"  {status_icon} {module}: {'已就绪' if is_ready else '未就绪'}")
        
        # 特别检查STT客户端
        print(f"🔍 STT客户端对象: {type(getattr(self.voice, 'stt_client', None))}")
        print(f"🔍 STT客户端存在: {hasattr(self.voice, 'stt_client') and self.voice.stt_client is not None}")
        
        if hasattr(self.voice, 'stt_client') and self.voice.stt_client:
            stt_client = self.voice.stt_client
            print(f"🔍 STT客户端配置: app_id={getattr(stt_client, 'app_id', 'Missing')[:8]}...")
            
        print("语音助手初始化成功！")
        return True
    
    def single_voice_interaction(self):
        """单次语音交互（唤醒后的一次问答）"""
        try:
            # 播放录音开始音效
            print("\n🔴 开始录音...")
            self.voice.play_system_sound("start_record")
            time.sleep(0.5)  # 等待音效播放完成
            
            # 启动VAD单段录制（录制完一段后自动停止）
            success, message, _ = self.voice.start_single_segment_recording(
                base_filename=f"demo_segment_{int(time.time())}"
            )
            
            if not success:
                print(f"❌ 启动录音失败: {message}")
                self.voice.play_system_sound("error")
                return
            
            print("🎤 正在录音中，检测到静音后自动停止...")
            
            # 等待录音完成
            while True:
                success_status, _, is_recording = self.voice.is_recording()
                if not success_status or not is_recording:
                    break
                time.sleep(0.1)
            
            # 获取录音结果
            success_stop, message_stop, result_file = self.voice.stop_recording()
            
            if success_stop and result_file:
                # 播放录音结束音效
                self.voice.play_system_sound("stop_record")
                print(f"📹 录制完成: {result_file}")
                
                # 语音识别
                if hasattr(self.voice, 'stt_client') and self.voice.stt_client:
                    print("🔄 正在进行语音识别...")
                    success_rec, message_rec, text = self.voice.recognize_audio_file(result_file)
                    
                    if success_rec and text:
                        print(f"✅ 识别结果: {text}")
                        self.voice.play_system_sound("success")
                        # 处理语音命令
                        self.process_voice_command(text)
                    else:
                        print(f"❌ 语音识别失败: {message_rec}")
                        self.voice.play_system_sound("error")
                else:
                    print("⚠️ 语音识别模块未初始化")
            else:
                print(f"❌ 录音失败: {message_stop}")
                self.voice.play_system_sound("error")
                
        except Exception as e:
            print(f"语音交互过程中发生错误: {e}")
            self.voice.play_system_sound("error")
            try:
                self.voice.stop_recording()
            except:
                pass
    
    def wake_detection_loop(self):
        """唤醒词检测循环"""
        print("[DEBUG] wake_detection_loop started")
        while self.is_running:
            try:
                # 检查是否检测到唤醒
                success, message, detected = self.voice.is_wake_detected()
                if not success:
                    print(f"[DEBUG] is_wake_detected failed: {message}")
                elif detected:
                    print("\n🎯 检测到唤醒词！")
                    self.wake_detected = True
                    
                    # 播放唤醒音效
                    print("播放唤醒音效...")
                    self.voice.play_system_sound("wake_up")
                    
                    # 暂停唤醒检测，进行单次语音交互
                    print("[DEBUG] Stopping wake detection for interaction")
                    self.voice.stop_wake_detection()
                    self.single_voice_interaction()
                    
                    # 重新启动唤醒检测
                    print("\n🎤 等待下一次唤醒词...")
                    print("[DEBUG] Restarting wake detection")
                    restart_success, restart_msg, _ = self.voice.start_wake_detection()
                    if not restart_success:
                        print(f"[DEBUG] Failed to restart wake detection: {restart_msg}")
                    else:
                        print("[DEBUG] Wake detection restarted successfully")
                    self.wake_detected = False
                else:
                    # 每10秒输出一次状态
                    if hasattr(self, '_debug_counter'):
                        self._debug_counter += 1
                    else:
                        self._debug_counter = 1
                    
                    if self._debug_counter % 100 == 0:  # 每10秒(100*0.1s)输出一次
                        print(f"[DEBUG] Wake detection loop running, no wake detected (count: {self._debug_counter})")
                    
                time.sleep(0.1)  # 避免过度占用CPU
                
            except Exception as e:
                print(f"[DEBUG] Exception in wake_detection_loop: {e}")
                import traceback
                traceback.print_exc()
                time.sleep(1)
    
    def start_recording_cycle(self):
        """开始录音识别循环（用于Windows测试环境）"""
        print("\n📝 开始语音录音识别循环...")
        
        while True:
            try:
                # 播放录音开始音效
                print("\n🔴 开始录音...")
                self.voice.play_system_sound("start_record")
                time.sleep(0.5)  # 等待音效播放完成
                
                # 启动VAD单段录制（录制完一段后自动停止）
                success, message, _ = self.voice.start_single_segment_recording(
                    base_filename=f"demo_segment_{int(time.time())}"
                )
                
                if not success:
                    print(f"❌ 启动录音失败: {message}")
                    self.voice.play_system_sound("error")
                    break
                
                print("🎤 正在录音中，检测到静音后自动停止...")
                print("💡 按Ctrl+C可手动停止录音")
                
                # 等待录音完成或用户中断
                try:
                    # 监听录音状态
                    while True:
                        success_status, _, is_recording = self.voice.is_recording()
                        if not success_status or not is_recording:
                            break
                        time.sleep(0.1)  # 减少检查间隔，提高响应速度
                        
                except KeyboardInterrupt:
                    print("\n⏹️ 用户手动停止录音")
                    self.voice.stop_recording()  # 确保停止录音
                    
                # 获取录音结果（单段录音自动停止后获取结果）
                success_stop, message_stop, result_file = self.voice.stop_recording()
                
                if success_stop and result_file:
                    # 播放录音结束音效
                    self.voice.play_system_sound("stop_record")
                    
                    print(f"📹 录制完成: {result_file}")
                    
                    # 语音转文字 - 添加详细调试信息
                    print(f"🔍 检查STT模块状态:")
                    print(f"  - hasattr(self.voice, 'stt_client'): {hasattr(self.voice, 'stt_client')}")
                    print(f"  - self.voice.stt_client: {getattr(self.voice, 'stt_client', None)}")
                    print(f"  - stt_client type: {type(getattr(self.voice, 'stt_client', None))}")
                    
                    if hasattr(self.voice, 'stt_client'):
                        stt_client = self.voice.stt_client
                        print(f"  - stt_client is not None: {stt_client is not None}")
                        if stt_client:
                            print(f"  - stt_client.app_id: {getattr(stt_client, 'app_id', 'Missing')[:8]}...")
                    
                    if hasattr(self.voice, 'stt_client') and self.voice.stt_client:
                        print("🔄 正在进行语音识别...")
                        success_rec, message_rec, text = self.voice.recognize_audio_file(result_file)
                        
                        if success_rec and text:
                            print(f"✅ 识别结果: {text}")
                            
                            # 播放成功音效
                            self.voice.play_system_sound("success")
                            
                            # 这里可以添加对识别结果的处理逻辑
                            self.process_voice_command(text)
                            
                        else:
                            print(f"❌ 语音识别失败: {message_rec}")
                            self.voice.play_system_sound("error")
                    else:
                        print("⚠️ 语音识别模块未初始化")
                        print(f"   原因分析: hasattr={hasattr(self.voice, 'stt_client')}, stt_client={getattr(self.voice, 'stt_client', None)}")
                    
                    # 询问是否继续
                    print("\n💬 请继续说话，或按Ctrl+C退出录音模式")
                    
                elif success_stop and not result_file:
                    print("⏰ 录音超时，未检测到语音")
                    break
                else:
                    print(f"❌ 停止录音失败: {message_stop}")
                    self.voice.play_system_sound("error")
                    break
                    
            except KeyboardInterrupt:
                print("\n👋 用户中断录音模式")
                # 确保停止录音
                try:
                    self.voice.stop_recording()
                except:
                    pass
                break
            except Exception as e:
                print(f"录音识别过程中发生错误: {e}")
                self.voice.play_system_sound("error")
                # 确保停止录音
                try:
                    self.voice.stop_recording()
                except:
                    pass
                break
    
    def process_voice_command(self, text):
        """处理语音命令（可扩展）"""
        print(f"🤖 处理语音命令: {text}")
        
        response_text = ""
        
        # 这里可以添加具体的命令处理逻辑
        # 例如：
        if "退出" in text or "结束" in text:
            response_text = "收到退出命令，再见！"
            print(f"🤖 {response_text}")
            self.speak_response(response_text)
            return False
        elif "你好" in text:
            response_text = "你好！我是语音助手，很高兴为您服务！"
            print(f"🤖 {response_text}")
            self.speak_response(response_text)
        elif "时间" in text:
            current_time = time.strftime("%Y年%m月%d日 %H:%M:%S")
            response_text = f"当前时间是 {current_time}"
            print(f"🕐 {response_text}")
            self.speak_response(response_text)
        else:
            response_text = "我听到了您的话，但还不知道如何回应。请尝试说你好或询问时间。"
            print(f"🤖 {response_text}")
            self.speak_response(response_text)
        
        return True
    
    def speak_response(self, text):
        """将文本转换为语音并播放"""
        try:
            print(f"🔊 正在播放语音回复: {text}")
            
            # 使用TTS功能将文本转换为语音并播放
            success, message, audio_file = self.voice.text_to_speech(text)
            
            if success and audio_file:
                print(f"✅ 语音合成成功，正在播放: {audio_file}")
                # 播放生成的音频文件
                play_success, play_message = self.voice.play_audio_file(audio_file)
                if play_success:
                    print("🎵 语音播放完成")
                else:
                    print(f"❌ 语音播放失败: {play_message}")
            else:
                print(f"❌ 语音合成失败: {message}")
                
        except Exception as e:
            print(f"❌ 语音回复过程中发生错误: {e}")
    
    def start(self):
        """启动语音助手"""
        if not self.initialize():
            return
        
        self.is_running = True
        
        try:
            # 尝试启动唤醒检测
            success, message, _ = self.voice.start_wake_detection()
            if not success:
                print(f"⚠️ 启动唤醒检测失败: {message}")
                print("🔄 跳过唤醒检测，直接进入录音模式（适用于Windows测试环境）")
                
                # 直接进入录音模式
                print("\n📝 开始语音录音识别模式...")
                print("💡 按Ctrl+C退出程序")
                self.start_recording_cycle()
                return
            
            print("\n🎤 语音助手已启动，正在等待唤醒词...")
            print("💡 说出唤醒词来激活语音助手")
            print("⏹️  按Ctrl+C退出程序")
            
            # 启动唤醒检测线程
            self.wake_thread = threading.Thread(target=self.wake_detection_loop)
            self.wake_thread.daemon = True
            self.wake_thread.start()
            
            # 主线程保持运行
            while self.is_running:
                time.sleep(1)
                
        except KeyboardInterrupt:
            print("\n👋 用户中断程序")
        except Exception as e:
            print(f"程序运行过程中发生错误: {e}")
        finally:
            self.stop()
    
    def stop(self):
        """停止语音助手"""
        print("\n🛑 正在停止语音助手...")
        
        self.is_running = False
        
        # 停止唤醒检测
        try:
            self.voice.stop_wake_detection()
        except:
            pass
        
        # 清理资源
        try:
            self.voice.cleanup()
        except:
            pass
        
        print("✅ 语音助手已停止")

def main():
    """主函数"""
    print("="*50)
    print("🤖 语音助手Demo")
    print("功能：唤醒词检测 -> 系统音效 -> VAD录音 -> 语音识别")
    print("="*50)
    
    assistant = VoiceAssistantDemo()
    assistant.start()

if __name__ == "__main__":
    main()